package la.bbs558.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import la.bbs558.dao.AdContentDao;
import la.bbs558.entity.AdContent;
import la.bbs558.entity.enums.AdPosition;
import la.bbs558.entity.enums.Sort;
import la.bbs558.entity.params.AdContentSearchPage;
import la.bbs558.satoken.StpAdminUtil;
import la.bbs558.service.AdContentService;
import la.bbs558.service.UserDataService;
import la.bbs558.util.Objs;
import la.bbs558.util.Strings;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class AdContentServiceImpl extends ServiceImpl<AdContentDao, AdContent> implements AdContentService {

    private final AdContentDao adContentDao;
    @Resource
    private UserDataService userDataService;

    @Override
    public List<AdContent> getAdsByPosition(Integer position, Long boardId) {
        boolean isBoardAd = AdPosition.LAYOUT_INNER.getCode().equals(position);
        Objs.isTrue(!isBoardAd || boardId != null, "版面广告必须传入版面id");
        if(AdPosition.HOME_BANNER.getCode().equals(position)){
            //增加访问次数
            userDataService.visit();
        }
        // 过滤开始时间和结束时间
        return adContentDao.selectAdContentByPosition(position, boardId, DateUtil.now());
    }

    @Override
    public void deleteAdContentForAdmin(Long id) {
        adContentDao.deleteById(id);
    }

    @Override
    public void addAdContentForAdmin(AdContent adContent) {
        adContent.setCreateUser(StpAdminUtil.getLoginIdAsLong());
        adContentDao.insert(adContent);
    }

    @Override
    public void selectAdContentPageForAdmin(AdContentSearchPage searchPage) {
        searchPage.setSortField(Strings.isEmpty(searchPage.getSortField()) ? "createTime" : searchPage.getSortField());
        Map<String, String> sortFieldMap = new HashMap<>();
        sortFieldMap.put("state", "state");
        sortFieldMap.put("startTime", "start_time");
        sortFieldMap.put("endTime", "end_time");
        sortFieldMap.put("createTime", "create_time");
        searchPage.setSortField(sortFieldMap.get(searchPage.getSortField()));
        searchPage.setSortMethod(Sort.ASC.getValue().equals(searchPage.getSortMethod()) ? Sort.ASC.getValue() : Sort.DESC.getValue());
        adContentDao.selectAdContentPageForAdmin(searchPage);
    }

    @Override
    public void updateAdContentForAdmin(AdContent adContent) {
        adContent.setCreateUser(null);
        adContent.setUpdateTime(null);
        adContent.setUpdateTime(null);
        adContent.setPosition(null);
        adContentDao.updateById(adContent);
    }
}
